
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';

import { ICategory } from 'src/types/category.interface';

type UnionType = ICategory | ICategory[];


@Injectable()
export class CategoryService {

    /**
     * 参数装饰器,CategoryTable 这个名字要和app.module.ts中的MongooseModule.forFeature 定义的名字一样
     * CategoryTable 是定义好的
     * @param recommendModel 
     */
    constructor(@InjectModel('CategoryTable') private categoryModel: Model<ICategory>) {

    }


    /**
     * 查询数据
     * @param queryCondition 
     * @returns 
     */
    async findService(queryCondition?:object): Promise<UnionType> {
        return this.categoryModel.find(queryCondition).exec();
    }


    /***
     * 向mongodb中插入数据
    */
    async importData(requestParamsBody: UnionType): Promise<UnionType> {
        //如果请求体是一个数组
        if (Array.isArray(requestParamsBody)) {
            return this.categoryModel.insertMany(requestParamsBody);
        }
        else {
            return new this.categoryModel(requestParamsBody).save();
        }
    }
}



